using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace ScottIsAFool.Common
{
    public class GetVideoCode
    {
        #region Declarations
        bool m_enabled;
        int m_defaultWidth;
        string m_link;
        int width;
        int height;        
        string vp;
        decimal ratio;
        bool other = false;
        bool allowsautoplay = false;
        static decimal googleratio = 400 / (decimal)326;
        static decimal yahooratio = 425 / (decimal)350;
        static decimal myspaceratio = 430 / (decimal)346;
        static decimal soapboxratio = 432 / (decimal)364;
        static decimal muveemixratio = 332 / (decimal)312;
        static decimal youtuberatio = 425 / (decimal)350;
        static decimal myvideoratio = 470 / (decimal)406;
        static decimal brightcoveratio = 486 / (decimal)412;
        static decimal divshareratio = 425 / (decimal)374;
        static decimal channel9ratio = 350 / (decimal)300;
        string id;
        string ap;
        int[] defaultwidth = { 425, 400, 430, 432, 332, 425, 470, 486, 425, 302 };
        int[] substrings = { 38, 0, 69, 36, 35, 31, 28, 42, 33 };
        int[] substrings2 = { 42, 0, 73, 40, 31, 27, 24, 38, 29 };
        string[] providers = { "yahoo", "google", "myspace", "soapbox", "muveemix", "youtube", "myvideo", "brightcove", "divshare", "channel9" };
        string[] autoplaycodes = { "", "&autoplay=1", "&a=1", "&ap=true", "", "&autoplay=1", "", "&autoStart=true", "", "<param name=\"autostart\" value=\"true\" />" };
        decimal[] ratios = { yahooratio, googleratio, myspaceratio, soapboxratio, muveemixratio, youtuberatio, myvideoratio, brightcoveratio, divshareratio, channel9ratio};
        string[] codes = { "<embed src=\"http://us.i1.yimg.com/cosmos.bcst.yahoo.com/player/media/swf/FLVVideoSolo.swf\"{3}{4}{5} flashvars=\"id=2365091&emailUrl=http%3A%2F%2Fvideo.yahoo.com%2Futil%2Fmail%3Fei%3DUTF-8%26vid%3D{2}&imUrl=http%25253A%25252F%25252Fvideo.yahoo.com%25252Fvideo%25252Fplay%25253Fei%25253DUTF-8%252526vid%25253D{2}&imTitle=Can%252526%25252339%25253Bt%252BTouch%252BMe%252B-%252BFamily%252BGuy&searchUrl=http://video.yahoo.com/video/search?p=&profileUrl=http://video.yahoo.com/video/profile?yid=&creatorValue=b2xkZXN0YnJlbWVyQHNiY2dsb2JhbC5uZXQ%3D&vid={2}\" type=\"application/x-shockwave-flash\" width=\"{0}\" height=\"{1}\"></embed>",
                           "<embed style=\"width:{0}px;{5} height:{1}px;\" id=\"VideoPlayback\" type=\"application/x-shockwave-flash\"{3} src=\"http://video.google.com/googleplayer.swf?docId={2}{4}\" flashvars=\"\"> </embed>",
                           "<embed src=\"http://lads.myspace.com/videos/vplayer.swf\"{5} flashvars=\"m={2}&type=video{4}\"{3} type=\"application/x-shockwave-flash\" width=\"{0}\" height=\"{1}\"></embed>",
                           "<embed src=\"http://images.video.msn.com/flash/soapbox1_1.swf\"{5} quality=\"high\" width=\"{0}\" height=\"{1}\"{3} type=\"application/x-shockwave-flash\" pluginspage=\"http://macromedia.com/go/getflashplayer\" flashvars=\"c=v&v={2}{4}\" ></embed>",
                           "<embed src=\"http://www.muveemix.com/flash/muveeloader.swf\"{5} flashvars=\"muveeid={2}{4}\" type=\"application/x-shockwave-flash\"{3} menu=\"false\" width=\"{0}\" height=\"{1}\" base=\"http://www.muveemix.com/flash/\"></embed>",
                           "<embed src=\"http://www.youtube.com/v/{2}{4}{5}\" type=\"application/x-shockwave-flash\"{3} width=\"{0}\" height=\"{1}\"></embed>",
                           "<embed src=\"http://www.myvideo.de/movie/{2}{4}\" width=\"{0}\"{5} height=\"{1}\" type=\"application/x-shockwave-flash\"{3}></embed>",
                           "<embed src=\"http://admin.brightcove.com/destination/player/player.swf\"{5} bgcolor=\"#FFFFFF\" flashVars=\"allowFullScreen=true&initVideoId={2}&servicesURL=http://www.brightcove.com&viewerSecureGatewayURL=https://www.brightcove.com&cdnURL=http://admin.brightcove.com\" base=\"http://admin.brightcove.com{4}\"{3} name=\"bcPlayer\" width=\"{0}\" height=\"{1}\" allowFullScreen=\"true\" allowScriptAccess=\"always\" seamlesstabbing=\"false\" type=\"application/x-shockwave-flash\" swLiveConnect=\"true\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"></embed>",
                           "<embed src=\"http://www.divshare.com/flash/video?myId={2}\"{3}{4}{5} width=\"{0}\" height=\"{1}\" name=\"divflv\" allowfullscreen=\"true\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></embed>",
                           "<object id=\"Player\" height=\"{1}\" width=\"{0}\"{3}{5} classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,0,5,0803\" type=\"application/x-oleobject\" viewastext=\"\"><param name=\"url\" value=\"{2}\" />{4}<param name=\"uiMode\" value=\"full\" /><param name=\"enabled\" value=\"true\" /></object>"};
        // String will have {0} = width, {1} = height, {2} = video code, {3} = transparent, {4} = autoplay, {5} = YouTube Rel Link
        #endregion

        public GetVideoCode(bool enabled, int width)
        {
            m_enabled = enabled;
            m_defaultWidth = width;
        }

        public string GetID
        {
            get { return id; }
        }

        public int GetHeight
        {
            get { return height; }
        }

        public int GetWidth
        {
            get { return width; }
        }

        public string GetProvider
        {
            get { return vp; }
        }

        public decimal GetRatio
        {
            get { return ratio; }
        }

        public string AutoPlay
        {
            get { return ap; }
        }

        public bool AllowAutoPlay
        {
            get { return allowsautoplay; }
        }

        public string Code
        {
            get
            {
                string c = "";
                for (int i = 0; i < providers.Length; i++)
                {
                    if (vp == providers[i])
                    {
                        if (vp == "google")
                        {
                            id = m_link.Substring(m_link.IndexOf("=") + 1);
                        }
                        else if (vp == "channel9")
                        {
                            id = m_link;
                        }
                        else
                        {
                            if (other)
                                id = m_link.Substring(substrings2[i]);
                            else
                                id = m_link.Substring(substrings[i]);
                        }

                        if (m_enabled)
                        {
                            width = m_defaultWidth;
                        }
                        else
                        {
                            width = defaultwidth[i];
                        }
                        height = (int)(width / ratios[i]);
                        ratio = ratios[i];
                        c = codes[i];
                        ap = autoplaycodes[i];
                        break;
                    }
                }
                return c;
            }
        }

        public string VideoProvider(string link)
        {
            m_link = link;
            vp = "";
            if (m_link.StartsWith("http://video.google") && m_link.Length > 45)
            {
                vp = "google";
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://www.video.google") && m_link.Length > 49)
            {
                vp = "google";
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://www.youtube") && m_link.Length > 41)
            {
                vp = "youtube";
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://youtube") && m_link.Length > 37)
            {
                vp = "youtube";
                other = true;
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://video.msn") && m_link.Length > 71)
            {
                vp = "soapbox";
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://www.video.msn") && m_link.Length > 75)
            {
                vp = "soapbox";
                other = true;
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://video.yahoo") && m_link.Length > 42)
                vp = "yahoo";
            else if (m_link.StartsWith("http://www.video.yahoo") && m_link.Length > 46)
            {
                vp = "yahoo";
                other = true;
            }
            else if (m_link.StartsWith("http://vids.myspace") && m_link.Length > 76)
            {
                vp = "myspace";
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://www.vids.myspace") && m_link.Length > 80)
            {
                vp = "myspace";
                other = true;
                allowsautoplay = true;
            }
            else if (m_link.StartsWith("http://www.muveemix") && m_link.Length > 36)
                vp = "muveemix";
            else if (m_link.StartsWith("http://muveemix") && m_link.Length > 32)
            {
                vp = "muveemix";
                other = true;
            }
            else if (m_link.StartsWith("http://www.myvideo.de") && m_link.Length > 22)
                vp = "myvideo";
            else if (m_link.StartsWith("http://myvideo.de") && m_link.Length > 22)
            {
                vp = "myvideo";
                other = true;
            }
            else if (m_link.StartsWith("http://www.brightcove.com") && m_link.Length > 50){
                vp = "brightcove";                
            }
            else if (m_link.StartsWith("http://brightcove.com") && m_link.Length > 46){
                vp = "brightcove";                
                other = true;
            }
            else if (m_link.StartsWith("http://www.divshare.com") && m_link.Length > 42)
            {
                vp = "divshare";
            }
            else if (m_link.StartsWith("http://divshare.com") && m_link.Length > 38)
            {
                vp = "divshare";
                other = true;
            }
            else if (m_link.StartsWith("http://channel9.msdn.com/Screencasts") && m_link.EndsWith(".wmv"))
            {
                vp = "channel9";
                allowsautoplay = true;
            }
            else
                vp = "na";

            return vp;
        }        

        public string GetHtmlPageSource
        {
            get
            {
                string t = "";
                if (vp == "channel9")
                {
                    t = "No Title";
                }
                else
                {
                    System.IO.Stream st = null;
                    System.IO.StreamReader sr = null;                    

                    try
                    {
                        // make a Web request
                        System.Net.WebRequest req = System.Net.WebRequest.Create(m_link);

                        // get the response and read from the result stream
                        System.Net.WebResponse resp = req.GetResponse();
                        st = resp.GetResponseStream();
                        sr = new System.IO.StreamReader(st);

                        // read all the text in it
                        t = sr.ReadToEnd();
                        t = GetTitle(t);
                    }
                    catch
                    {
                        return string.Empty;
                    }
                    finally
                    {
                        // always close readers and streams
                        sr.Close();
                        st.Close();
                    }
                }
                return t;
            }
        }

        public string GetTitle(string Source)
        {
            string tag = "<title";
            string title = "      ";
            int len = Source.Length;
            
            char c;
            for (int i = 0; i < len; i++)
            {
                c = Convert.ToChar(Source.Substring(i, 1));
                title = title.Remove(0, 1);
                title += c;
                if (title.ToLower() == tag)
                {
                    while (c != '>')
                    {
                        i++;
                        c = Convert.ToChar(Source.Substring(i, 1));
                    }
                    title = "";
                    i++;
                    c = Convert.ToChar(Source.Substring(i, 1));
                    while (c != '<')
                    {
                        title += c;
                        i++;
                        c = Convert.ToChar(Source.Substring(i, 1));
                    }
                    break;
                }
            }
            return title.Trim();
        }

    }
}
